<?php

App::import('Model', 'PaymentDue');
App::import('Model', 'Property');
App::import('Model', 'Person');
App::import('Model', 'Building');
App::import('Model', 'Account');

class ExpensesController extends AppController {

    var $name = 'Expenses';
    var $paginate = null;

    function index() {
        //	$permit  = $this->Session->read('permit_property');
        //if ($permit != null){
        //	$month_current = date('m');
        //	$year_current  = date('Y');
        //	$data = null;
        //	$new  = null;
        //	foreach ($permit as $key => $value) {
        //      $this->paginate = array('conditions' => array('Expense.property_id' => $value['property_id'],
        //														  'YEAR(Expense.created)' => $year_current,
        //                                                  'MONTH(Expense.created)' =>$month_current)
        //                       );
        //			if ($this->paginate != null )
        //				$data[$key]  = $this->paginate();
        //		}
        //		foreach ( $data as $key1 => $value1)
        //		{
        //			if ($value1 != null)
        //				$new[$key1] = $value1[0];
        //		}
        //			$this->set('expenses', $new);
        //	}else{
        //	  $this->Session->setFlash(__('You have nothing assigned', true));
        //	  $this->redirect(array('controller' => 'users', 'action' => 'welcome'));
        //	}
        $this->Expense->recursive = 0;
        $this->set('expenses', $this->paginate());
    }

    function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid expense', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('expense', $this->Expense->read(null, $id));
    }

    function add() {
        if (!empty($this->data)) {
            $this->Expense->create();
            if ($this->Expense->save($this->data)) {
                $this->Session->setFlash(__('The expense has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The expense could not be saved. Please, try again.', true));
            }
        }
        $properties = $this->Expense->Property->find('list');
        $refinancingPlans = $this->Expense->RefinancingPlan->find('list');
        $expenditureTypeSources = $this->Expense->ExpenditureTypeSource->find('list',
                        array('conditions' => array('ExpenditureTypeSource.lookup_type' => 'EXPENDITURE_TYPE_SOURCE')));
        $this->set(compact('properties', 'refinancingPlans', 'expenditureTypeSources'));
    }

    function edit($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid expense', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->Expense->save($this->data)) {
                $this->Session->setFlash(__('The expense has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The expense could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Expense->read(null, $id);
        }
        $properties = $this->Expense->Property->find('list');
        $refinancingPlans = $this->Expense->RefinancingPlan->find('list');
        $expenditureTypeSources = $this->Expense->ExpenditureTypeSource->find('list',
                        array('conditions' => array('ExpenditureTypeSource.lookup_type' => 'EXPENDITURE_TYPE_SOURCE')));
        $this->set(compact('properties', 'refinancingPlans', 'expenditureTypeSources'));
    }

    function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for expense', true));
            $this->redirect(array('action' => 'index'));
        }
        $expen = $this->Expense->read(null, $id);
        if ($expen['Expense']['payment_date'] == null) {
            if ($this->Expense->delete($id)) {
                $this->Session->setFlash(__('Expense deleted', true));
                $this->redirect(array('action' => 'index'));
            }
        } else {
            $this->Session->setFlash(__('This expense can not be deleted because it has already been paid', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Expense was not deleted', true));
        $this->redirect(array('action' => 'index'));
    }

    function get_name_people($property_id) {
        $property = new Property;
        $id_occupant = $property->get_occupant($property_id);
        $people = new Person;
        $peoples = $people->read(null, $id_occupant);
        $name = $peoples['Person']['first_name'];
        $surname = $peoples['Person']['surname'];
        $complete_name = $surname . ', ' . $name;
        return $complete_name;
    }

    function get_property_id($exp_id) {
        $expen = $this->Expense->read(null, $exp_id);
        return($expen['Property']['property_id']);
    }

    function get_mail_people($property_id) {
        $property = new Property;
        $id_occupant = $property->get_occupant($property_id);
        $people = new Person;
        $peoples = $people->read(null, $id_occupant);
        return ($peoples['Person']['email']);
    }

    function pay($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid expense', true));
            $this->redirect(array('action' => 'index'));
        }
        // Pago de la expensa
        if (!empty($this->data)) {
            // Levanto la data
            $amount = $this->data['Expense']['expenses']; // Expensa del mes
            $previous_due = $this->data['Expense']['previous_due']; // Monto adeudado
            $total_interest = $this->data['Expense']['total_interest']; // Intereses
            $month_new_interests = $this->data['Expense']['month_new_interests'];
            $next_month_interests = $this->data['Expense']['next_month_interests'];
            $payment_on_account = $this->data['Expense']['payment_on_account']; // Pagado hasta el momento
            $total = $this->data['Expense']['total']; // Total adeudado por la propiedad
            $payment = $this->data['Expense']['payment']; // monto ingresado a pagar
            $interests_debt = $this->data['Expense']['interests_debt'];
            $amount_debt = $this->data['Expense']['amount_debt'];
            $expense_debt = $this->data['Expense']['expense_debt'];
            
            // Verificaciones
            // La deuda total debe ser mayor a 0
            if ($total <= 0) {
                $this->Session->setFlash(__('Payment is complete.', true));
                $this->redirect(array('action' => 'index'));
            }
            // El monto ingresado debe ser como mínimo el total de los intereses adeudados
            if ($payment < $interests_debt){
                $this->Session->setFlash(__('The payment, at least, must cover the interest amount.', true));
				$this->redirect(array('action' => 'pay', $this->data["Expense"]["id"]));
			}

            // Obtengo los registros a modificar
            $expense_data = $this->Expense->read(null, $this->data['Expense']['id']);
            $build = new Building;
            $build_data = $build->read(null, $expense_data['Property']['building_id']);
            $property = new Property();
            $property_data = $property->read(null, $expense_data['Property']['property_id']);
            $account = new Account();
            $account_data = $account->read(null, $property_data['Account']['account_id']);

            $aux = $payment;
            $expenditure_type = $this->Expense->getExpenditureTypeSource($expense_data['Expense']);
            $scheme = $this->Expense->getBuildingInterestScheme($build_data['PaymentDue']);
            // Descuento los intereses
            // OBS: si hay pago diferido de intereses, y hay atraso, se agregan, sino se resta 0
            if ($interests_debt > 0){
                if (($expenditure_type == "REGULAR") && ($scheme == 'DEFERRED')){
                    $account_data['Account']['regular_interests_balance'] += $next_month_interests;
                } else if (($expenditure_type == "REGULAR") && ($scheme != 'DEFERRED')){
                    $account_data['Account']['regular_interests_balance'] = 0;
                } else if (($expenditure_type == "SPECIAL") && ($scheme == 'DEFERRED')){
                    $account_data['Account']['special_interest_balance'] += $next_month_interests;
                }  else if (($expenditure_type == "SPECIAL") && ($scheme != 'DEFERRED')){
                    $account_data['Account']['special_interest_balance'] = 0;
                }
                $aux -= $interests_debt;
            }
            // Si queda descuento de la deuda previa si falta
            if (($amount_debt > 0) && ($aux > 0)){
                $amount_debt_payment = min($aux, $amount_debt);
                if ($expenditure_type == "REGULAR"){
                    $account_data['Account']['regular_expense_balance'] += $amount_debt_payment;
                } else {
                    $account_data['Account']['special_expense_balance'] += $amount_debt_payment;
                }
                $aux -= $amount_debt_payment;
            }
            // Si queda descuento del monto de la expensa
            if (($expense_debt > 0) && ($aux > 0)){
                $expense_debt_payment = min($aux, $expense_debt);
                if ($expenditure_type == "REGULAR"){
                    $account_data['Account']['regular_expense_balance'] += $expense_debt_payment;
                } else {
                    $account_data['Account']['special_expense_balance'] += $expense_debt_payment;
                }
                $aux -= $expense_debt_payment;
            }
            // Ya termine de pagar. Si sobra plata se la doy de vuelto
            $change = $aux;
            $payment -= $aux;
            $expense_data['Expense']['payment_amount'] += $payment;
            
            $expense_data['Expense']['interests'] += $month_new_interests;
            // Sumo a los fondos del edificio
            if ($expenditure_type == "REGULAR"){
                $build_data['Building']['regular_fund'] += $payment;
            } else {
                $build_data['Building']['special_fund'] += $payment;
            }
            // Si se paga en segundo vencimiento (si hay) y antes no se había
            // realizado un pago en este periodo, se suma el recargo a la cuenta
            // de la propiedad
            if ($scheme == "SECOND_DUE_DATE") {
                $format = date("Y") . '-' . date("m") . '-' . 1;
                $last_payment_date = new DateTime($format);
                if (!is_null($expense_data['Expense']['payment_date'])){
                    $last_payment_date = new DateTime($expense_data['Expense']['payment_date']);
                }
                $today = new DateTime(date("Y-m-d"));
                $first_due_date = new DateTime($this->Expense->getFirstDueDate($build_data['PaymentDue']));

                $payment_gap = $this->Expense->getDatePeriodGap($first_due_date,$last_payment_date);
                $current_gap = $this->Expense->getDatePeriodGap($first_due_date,$today);

                if (($payment_gap < 0) && ($current_gap > 0)){
                    $diff = $expense_data['Expense']['second_due_amount'] - $expense_data['Expense']['amount'];
                    if ($expenditure_type == "REGULAR"){
                        $account_data['Account']['regular_expense_balance'] -= $diff;
                    } else {
                        $account_data['Account']['special_expense_balance'] -= $diff;
                    }
                }
            }
            $expense_data['Expense']['payment_date'] = date('Y-m-d');

            // Guardo todos los cambios
            // Account
            $account->save($account_data);
            // Building
            $build->save($build_data);
            // Expense
            $this->Expense->save($expense_data);

            if ($change > 0){
                $this->Session->setFlash(__('Payment done. Your change is $'.$change, true));
            }
            else {
                $this->Session->setFlash(__('Payment done ', true));
            }
            $this->redirect(array('action' => 'index'));
        }
        // Seteo de informacion para la pantalla de pago
        else if (empty($this->data)) {
            $expen = $this->Expense->read(null, $id);
            if (!$id && empty($this->data)) {
                $this->Session->setFlash(__('Invalid expense', true));
                $this->redirect(array('action' => 'index'));
            }
            // Levanto monto, deuda previa e intereses
            $expenseFinantialInfo = array();
            $expenseFinantialInfo = $this->Expense->getExpenseFinantialInformation($expen);

            if ($expenseFinantialInfo['debt'] == 0) {
                $this->Session->setFlash(__('Payment is complete.', true));
                $this->redirect(array('action' => 'index'));
            }
            else if ($expenseFinantialInfo['payment_amount'] > 0){
                $this->Session->setFlash(__('The Expense has been paid a totaling ' . $expenseFinantialInfo['payment_amount'], true));
            }

            $this->set('status', 'disabled');
            $this->set('status1', 'enabled');

            //******************************************************************
            // Datos de la propiedad
            $this->data['Expense']['id'] = $id;
            $property_id = $expen['Property']['property_id'];
            //Obtengo el nombre del que esta ocupando la propiedad
            $name_occupant = $this->get_name_people($property_id);
            $this->set('complete_name', $name_occupant);
            //******************************************************************
            // Informacion financiera
            $this->data['Expense']['interest(%)'] = round($expenseFinantialInfo['interest(%)'],4);
            // Monto a pagar
            $this->data['Expense']['expenses'] = round($expenseFinantialInfo['amount'], 2);
            // Monto adeudado
            $this->data['Expense']['previous_due'] = round($expenseFinantialInfo['previous_debt'], 2);
            // Intereses a pagar con esta expensa
            $this->data['Expense']['total_interest'] = round($expenseFinantialInfo['interests'], 2);
            // Intereses agregados
            $this->data['Expense']['next_month_interests'] = round($expenseFinantialInfo['next_month_interests'], 2);
            $this->data['Expense']['month_new_interests'] = round($expenseFinantialInfo['month_new_interests'], 2);
            // Pagado hasta el momento
            $this->data['Expense']['payment_on_account'] = round( $expenseFinantialInfo['payment_amount'], 2);
            // Total adeudado por la propiedad
            $this->data['Expense']['interests_debt'] = round( $expenseFinantialInfo['interests_debt'], 2);
            $this->data['Expense']['amount_debt'] = round( $expenseFinantialInfo['amount_debt'], 2);
            $this->data['Expense']['expense_debt'] = round( $expenseFinantialInfo['expense_debt'], 2);
            $this->data['Expense']['total'] = round($expenseFinantialInfo['debt'], 2);
            //******************************************************************
        }
    }

    function report($id = null) {

        $filetmp = '../tmp/expenses/id-' . $id . '-' . date("Y-m") . '.pdf';
        if (!$id) {
            $this->Session->setFlash('Sorry, there was no PDF selected.');
            $this->redirect(array('action' => 'index'), null, true);
        }

        // Leo todos los datos de la expensa.
        $expense = $this->Expense->read(null, $id);
        // Agarro el building_id
        /*$build_id = $expense['Property']['building_id'];
        // Traigo la fecha del 2 vencimiento
        $second_date = $this->get_second_date($build_id);
        // Me fijo si paga atrasado
        $gap_day = $this->Expense->gapDates($second_date);
        if ($gap_day > 0) {
            $interets = $this->Expense->recalculateAmount($expense['Expense']['interests'], $gap_day);
        } else {
            $interets = 0;
        }
        $inter = ( $expense['Expense']['second_due_amount'] * $interets ) / 100;
         */

        // Otherwise we cannot use this method while developing
        Configure::write('debug', 3);

        $nameOccupant = $this->get_name_people($expense['Expense']['property_id']);
        $typeExpense = $expense['Expense']['expenditure_type_source'];
        $dateExpense = substr($expense['Expense']['created'],0,10);
        $debtAmount = round($expense['Expense']['previous_debt'], 2);
        $interests = round($expense["Expense"]["interests"], 2);
        $expenseAmount = round($expense['Expense']['amount'], 2);
        $total = round($debtAmount + $interests + $expenseAmount, 2);

        if ($typeExpense == '6') { // SPECIAL
            $typeExpense = 'Extraordinarias';
        } else {
            $typeExpense = 'Ordinarias';
        }

        $this->set(compact('nameOccupant', 'dateExpense', 'debtAmount', 'interests', 'expenseAmount', 'total'));
        $this->set('typeExpense', $typeExpense);
        $this->set('filetmp', $filetmp);
        $this->render('report');
        return ($filetmp);
    }

}

?>
